package com.imooc.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.imooc.entity.*;
import com.imooc.service.BookService;
import com.imooc.service.CategoryService;
import com.imooc.service.EvaluationService;
import com.imooc.service.MemberService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class BookController {
    @Resource
    private CategoryService categoryService;

    @Resource
    private BookService bookService;

    @Resource
    private EvaluationService evaluationService;

    @Resource
    private MemberService memberService;

    @GetMapping("/")
    public ModelAndView showIndex() {
        ModelAndView modelAndView = new ModelAndView("/index");
        List<Category> categories = categoryService.selectAll();
        modelAndView.addObject("categories", categories);
        return modelAndView;
    }

    @GetMapping("/books")
    @ResponseBody
    public IPage<Book> books(Long categoryId, String order, Integer p) {
        if (p == null) {
            p = 1;
        }
        return bookService.paging(categoryId, order, p, 10);
    }

    @GetMapping("/book/{bookId}")
    public ModelAndView bookDetail(@PathVariable("bookId") Long bookId, HttpSession httpSession) {
        ModelAndView modelAndView = new ModelAndView("/detail");
        Book book = bookService.getById(bookId);
        Member loginMember = (Member) httpSession.getAttribute("loginMember");
        if (loginMember != null) {
            // 获取会员阅读状态
            MemberReadState memberReadState = memberService.selectMemberReadState(loginMember.getMemberId(), bookId);
            modelAndView.addObject("memberReadState", memberReadState);
        }
        List<Evaluation> evaluations = new ArrayList<>();
        if (book != null) {
            evaluations = evaluationService.selectByBookId(bookId);
        }
        modelAndView.addObject("book", book);
        modelAndView.addObject("evaluations", evaluations);
        return modelAndView;
    }

}
